package net.spmiller;

import net.spmiller.exception.FlickrInterfaceException;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.Properties;

public class FlickrConversation {
    private String frob;
    private boolean authorised = false;
    private String token;
    private static final String FROB_PROPERTY = "frob";
    private static final String TOKEN_PROPERTY = "token";
    private static final String AUTHORISED_PROPERTY = "authorised";

    private FlickrConversation(String frob) {
        this.frob = frob;
    }

    public static FlickrConversation conversationFromFrob(String frob) {
        return new FlickrConversation(frob);
    }

    public static FlickrConversation conversationFromToken(String token) {
        FlickrConversation conversation = new FlickrConversation(null);
        conversation.authoriseConversation(token);
        return conversation;
    }

    public String getFrob() {
        return frob;
    }

    public boolean isAuthorised() {
        return authorised;
    }

    public String getToken() {
        if (!authorised) {
            throw new FlickrInterfaceException("This conversation does not have a token as it has not yet been authorised.");
        }
        return token;
    }

    public void authoriseConversation(String token) {
        this.token = token;
        this.authorised = true;
        this.frob = null;
    }

    public void saveToFile(Writer writer) throws IOException {
        Properties properties = new Properties();
        properties.setProperty(AUTHORISED_PROPERTY, Boolean.toString(isAuthorised()));
        if (isAuthorised()) {
            properties.setProperty(TOKEN_PROPERTY, token);
        } else {
            properties.setProperty(FROB_PROPERTY, frob);
        }

        properties.store(writer, "FlickrConversation");
    }

    public static FlickrConversation deserialise(Reader reader) throws IOException {
        Properties properties = new Properties();
        properties.load(reader);

        boolean authorised = Boolean.valueOf(properties.getProperty(AUTHORISED_PROPERTY, String.valueOf(false)));

        if (authorised) {
            return conversationFromToken(properties.getProperty(TOKEN_PROPERTY));
        } else {
            return conversationFromFrob(properties.getProperty(FROB_PROPERTY));
        }
    }
}
